package com.imooc.distributedemo.resume;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 利用ReentrantLock锁的方式  交替打印奇偶数
 */
public class SequentialPrinterWithLock {

    private static final Lock lock = new ReentrantLock();
    private static final Condition oddCondition = lock.newCondition();
    private static final Condition evenCondition = lock.newCondition();

    private static int number = 1;
    private static final int MAX_VALUE = 100;

    public static void main(String[] args) {
        Thread oddThread = new Thread(new OddPrinter());
        Thread evenThread = new Thread(new EvenPrinter());
        oddThread.start();
        evenThread.start();
    }


    static class OddPrinter implements Runnable {

        @Override
        public void run() {
            while (number < MAX_VALUE){
                lock.lock();
                try{
                    if(number % 2 == 0){
                        oddCondition.await();
                    }
                    // 打印奇数
                    System.out.println(Thread.currentThread().getName()+"--print--"+number);

                    number ++;
                    evenCondition.signal();
                }catch (InterruptedException e){
                    e.printStackTrace(); // 简单处理 ，业务系统不允许
                }finally {
                    lock.unlock();
                }
            }
        }
    }

    static class EvenPrinter implements Runnable {

        @Override
        public void run() {
            while (number < MAX_VALUE){
                lock.lock();
                try{
                    if(number % 2 != 0){
                        evenCondition.await();
                    }
                    // 打印奇数
                    System.out.println(Thread.currentThread().getName()+"--print--"+number);

                    number ++;
                    oddCondition.signal();
                }catch (InterruptedException e){
                    e.printStackTrace(); // 简单处理 ，业务系统不允许
                }finally {
                    lock.unlock();
                }
            }
        }
    }
}
